package com.inputabc.ct.v1.ui;

import com.inputabc.ct.v1.setting.KeySetting;
import com.inputabc.ct.v1.setting.SettingContext;
import com.inputabc.ct.v1.setting.TextBoxSetting;
import com.inputabc.ct.v1.setting.TranslateSetting;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

public class SettingsDialog extends JDialog {
    private JTabbedPane tabbedPane;
    private JPanel appearancePanel;
    private JPanel translationPanel;
    private JPanel apiKeysPanel;
    private JPanel buttonPanel;
    private JButton applyButton;
    private JButton cancelButton;
    
    // 全局引用TextBox，在应用设置时使用
    private TextBox textBox;
    
    // 设置对象
    private TextBoxSetting textBoxSetting = SettingContext.textBoxSetting;
    private TranslateSetting translateSetting = SettingContext.translateSetting;
    private KeySetting keySetting = SettingContext.keySetting;
    
    // 配置文件路径
    public final static String SETTING_CONF = "settings.conf";
    
    // 外观设置组件
    private JTextField fontSizeField;
    private JComboBox<String> fontFamilyCombo;
    private JComboBox<String> fontStyleCombo;
    private JButton textColorButton;
    private JButton backgroundColorButton;
    private JSlider opacitySlider;
    private JButton backgroundImageButton;
    private JRadioButton enableBgImageRadio;
    private JRadioButton disableBgImageRadio;
    private JComboBox<String> borderStyleCombo;
    
    // 翻译设置组件
    private JRadioButton youdaoRadio;
    private JRadioButton baiduRadio;
    private JRadioButton googleRadio;
    // 注释掉DeepSeek选项，隐藏但保留代码
    // private JRadioButton deepSeekRadio;
    private JRadioButton qianfanRadio;
    private JComboBox<String> translationDirectionCombo;
    
    // API密钥设置组件
    private JTextField youdaoAppKeyField;
    private JTextField youdaoAppSecretField;
    private JTextField baiduAppIdField;
    private JTextField baiduSecurityKeyField;
    private JTextField googleApiKeyField;
    
    // 颜色设置
    private Color textColor;
    private Color backgroundColor;
    
    // 背景图片设置
    private String backgroundImagePath;
    private boolean useBackgroundImage;
    
    // 翻译引擎选项区域
    private JLabel engineLabel;
    
    /**
     * 创建设置对话框
     * @param parent 父窗口
     * @param textBox TextBox实例
     */
    public SettingsDialog(JFrame parent, TextBox textBox) {
        super(parent, "设置", true);
        this.textBox = textBox;
        
        // 初始化组件
        initComponents();
        
        // 加载当前设置
        loadCurrentSettings();
        
        // 确保背景图片设置区域的状态与边框样式一致
        updateBackgroundImageSettingsState();
        
        // 设置对话框属性
        setSize(600, 500);
        setLocationRelativeTo(parent);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    }
    
    /**
     * 初始化对话框组件
     */
    private void initComponents() {
        // 设置对话框布局
        setLayout(new BorderLayout(10, 10));
        
        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setFont(new Font("Dialog", Font.PLAIN, 12));
        
        // ======== 外观设置面板 ========
        JPanel appearancePanel = new JPanel(new BorderLayout(10, 10));
        appearancePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // -------- 字体设置面板 --------
        JPanel fontPanel = new JPanel();
        fontPanel.setLayout(new BoxLayout(fontPanel, BoxLayout.Y_AXIS));
        fontPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "字体设置", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        // 字体名称行
        JPanel fontNameRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel fontNameLabel = new JLabel("字体名称:");
        fontNameLabel.setPreferredSize(new Dimension(80, 22));
        fontNameRow.add(fontNameLabel);
        
        // 获取系统字体列表
        String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
        fontFamilyCombo = new JComboBox<>(fontNames);
        fontFamilyCombo.setPreferredSize(new Dimension(220, 25));
        fontNameRow.add(fontFamilyCombo);
        fontPanel.add(fontNameRow);
        
        // 字体大小行
        JPanel fontSizeRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel fontSizeLabel = new JLabel("字体大小:");
        fontSizeLabel.setPreferredSize(new Dimension(80, 22));
        fontSizeRow.add(fontSizeLabel);
        
        fontSizeField = new JTextField("16");
        fontSizeField.setPreferredSize(new Dimension(50, 25));
        fontSizeRow.add(fontSizeField);
        fontPanel.add(fontSizeRow);
        
        // 字体样式行
        JPanel fontStyleRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel fontStyleLabel = new JLabel("字体样式:");
        fontStyleLabel.setPreferredSize(new Dimension(80, 22));
        fontStyleRow.add(fontStyleLabel);
        
        String[] styles = {"常规", "粗体", "斜体", "粗斜体"};
        fontStyleCombo = new JComboBox<>(styles);
        fontStyleCombo.setPreferredSize(new Dimension(100, 25));
        fontStyleRow.add(fontStyleCombo);
        fontPanel.add(fontStyleRow);
        
        // -------- 颜色设置面板 --------
        JPanel colorPanel = new JPanel();
        colorPanel.setLayout(new BoxLayout(colorPanel, BoxLayout.Y_AXIS));
        colorPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "颜色设置", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        // 文字颜色行
        JPanel textColorRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel textColorLabel = new JLabel("文字颜色:");
        textColorLabel.setPreferredSize(new Dimension(80, 22));
        textColorRow.add(textColorLabel);
        
        textColorButton = new JButton("选择颜色");
        textColorButton.setPreferredSize(new Dimension(120, 28));
        textColorButton.addActionListener(e -> {
            Color selectedColor = JColorChooser.showDialog(this, "选择文字颜色", textColor);
            if (selectedColor != null) {
                textColor = selectedColor;
                textColorButton.setBackground(textColor);
                // 设置合适的前景色以保证按钮文字可读
                textColorButton.setForeground(getContrastColor(textColor));
            }
        });
        textColorRow.add(textColorButton);
        colorPanel.add(textColorRow);
        
        // 背景颜色行
        JPanel bgColorRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel bgColorLabel = new JLabel("背景颜色:");
        bgColorLabel.setPreferredSize(new Dimension(80, 22));
        bgColorRow.add(bgColorLabel);
        
        backgroundColorButton = new JButton("选择颜色");
        backgroundColorButton.setPreferredSize(new Dimension(120, 28));
        backgroundColorButton.addActionListener(e -> {
            Color selectedColor = JColorChooser.showDialog(this, "选择背景颜色", backgroundColor);
            if (selectedColor != null) {
                backgroundColor = selectedColor;
                backgroundColorButton.setBackground(backgroundColor);
                // 设置合适的前景色以保证按钮文字可读
                backgroundColorButton.setForeground(getContrastColor(backgroundColor));
            }
        });
        bgColorRow.add(backgroundColorButton);
        colorPanel.add(bgColorRow);
        
        // -------- 透明度设置面板 --------
        JPanel opacityPanel = new JPanel();
        opacityPanel.setLayout(new BoxLayout(opacityPanel, BoxLayout.Y_AXIS));
        opacityPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "透明度设置", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        JPanel opacityRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        opacityRow.add(new JLabel("窗口透明度:"));
        
        // 创建透明度滑块，范围从20到100（对应0.2到1.0的透明度）
        opacitySlider = new JSlider(JSlider.HORIZONTAL, 20, 100, 100);
        opacitySlider.setMajorTickSpacing(20);
        opacitySlider.setMinorTickSpacing(5);
        opacitySlider.setPaintTicks(true);
        opacitySlider.setPaintLabels(true);
        opacitySlider.setPreferredSize(new Dimension(320, 50));
        
        // 添加实时预览功能
        opacitySlider.addChangeListener(e -> {
            if (textBox != null) {
                JFrame frame = textBox.getJFrame();
                if (frame != null) {
                    float opacity = opacitySlider.getValue() / 100.0f;
                    System.out.println("尝试设置透明度: " + opacity);
                    
                    // 确保窗口是无装饰的
                    if (!frame.isUndecorated()) {
                        System.out.println("窗口不是无装饰的，正在设置...");
                        frame.dispose();
                        frame.setUndecorated(true);
                        frame.setVisible(true);
                    }
                    
                    try {
                        textBox.safelySetOpacity(frame, opacity);
                        textBoxSetting.setOpacity(opacity);
                        System.out.println("透明度设置成功: " + frame.getOpacity());
                    } catch (Exception ex) {
                        System.err.println("设置透明度时出错: " + ex.getMessage());
                        ex.printStackTrace();
                    }
                } else {
                    System.err.println("无法获取窗口引用");
                }
            } else {
                System.err.println("TextBox引用为空");
            }
        });
        
        opacityRow.add(opacitySlider);
        opacityPanel.add(opacityRow);
        
        // -------- 边框样式设置面板 --------
        JPanel borderPanel = new JPanel();
        borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.Y_AXIS));
        borderPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "边框样式设置", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        JPanel borderRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel borderLabel = new JLabel("边框样式:");
        borderLabel.setPreferredSize(new Dimension(80, 22));
        borderRow.add(borderLabel);
        
        String[] borderStyles = {"无边框", "简单边框", "凸起边框", "凹陷边框", "蚀刻边框", "科技边框", "终端边框"};
        borderStyleCombo = new JComboBox<>(borderStyles);
        borderStyleCombo.setPreferredSize(new Dimension(120, 25));
        
        // 添加边框样式改变监听器
        borderStyleCombo.addActionListener(e -> {
            // 当边框样式改变时，更新背景图片设置区域的状态
            updateBackgroundImageSettingsState();
        });
        
        borderRow.add(borderStyleCombo);
        borderPanel.add(borderRow);
        
        // -------- 背景图片设置面板 --------
        JPanel bgImagePanel = new JPanel();
        bgImagePanel.setLayout(new BoxLayout(bgImagePanel, BoxLayout.Y_AXIS));
        bgImagePanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "背景图片设置", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        // 背景图片选择行
        JPanel bgImageRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        bgImageRow.add(new JLabel("选择图片:"));
        
        backgroundImageButton = new JButton("浏览...");
        backgroundImageButton.setPreferredSize(new Dimension(120, 28));
        backgroundImageButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("选择背景图片");
            fileChooser.setFileFilter(new FileNameExtensionFilter("图片文件", "jpg", "jpeg", "png", "gif"));
            
            int result = fileChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                backgroundImagePath = selectedFile.getAbsolutePath();
                backgroundImageButton.setText("已选择图片");
                enableBgImageRadio.setSelected(true);
            }
        });
        bgImageRow.add(backgroundImageButton);
        bgImagePanel.add(bgImageRow);
        
        // 背景图片启用/禁用行
        JPanel bgImageOptionRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        enableBgImageRadio = new JRadioButton("启用背景图片");
        disableBgImageRadio = new JRadioButton("禁用背景图片");
        
        enableBgImageRadio.setFont(new Font("Dialog", Font.PLAIN, 12));
        disableBgImageRadio.setFont(new Font("Dialog", Font.PLAIN, 12));
        
        ButtonGroup bgImageGroup = new ButtonGroup();
        bgImageGroup.add(enableBgImageRadio);
        bgImageGroup.add(disableBgImageRadio);
        
        bgImageOptionRow.add(enableBgImageRadio);
        bgImageOptionRow.add(Box.createHorizontalStrut(20));
        bgImageOptionRow.add(disableBgImageRadio);
        bgImagePanel.add(bgImageOptionRow);
        
        // 添加到外观面板
        JPanel appearanceContent = new JPanel();
        appearanceContent.setLayout(new BoxLayout(appearanceContent, BoxLayout.Y_AXIS));
        
        appearanceContent.add(fontPanel);
        appearanceContent.add(Box.createVerticalStrut(10));
        appearanceContent.add(colorPanel);
        appearanceContent.add(Box.createVerticalStrut(10));
        appearanceContent.add(opacityPanel);
        appearanceContent.add(Box.createVerticalStrut(10));
        appearanceContent.add(borderPanel);
        appearanceContent.add(bgImagePanel);
        
        // 使用滚动面板，以防窗口太小
        JScrollPane appearanceScrollPane = new JScrollPane(appearanceContent);
        appearanceScrollPane.setBorder(null);
        appearanceScrollPane.getVerticalScrollBar().setUnitIncrement(16);
        appearancePanel.add(appearanceScrollPane, BorderLayout.CENTER);
        
        // ======== 翻译设置面板 ========
        JPanel translationPanel = new JPanel(new BorderLayout(10, 10));
        translationPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        JPanel translationContent = new JPanel();
        translationContent.setLayout(new BoxLayout(translationContent, BoxLayout.Y_AXIS));
        
        // -------- 翻译引擎设置面板 --------
        JPanel enginePanel = new JPanel();
        enginePanel.setLayout(new BoxLayout(enginePanel, BoxLayout.Y_AXIS));
        enginePanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "翻译引擎", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        JPanel engineRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        
        // 创建翻译引擎选项
        engineLabel = new JLabel("翻译引擎:");
        youdaoRadio = new JRadioButton("有道翻译");
        baiduRadio = new JRadioButton("百度翻译");
        googleRadio = new JRadioButton("谷歌翻译");
        // 注释掉DeepSeek选项，隐藏但保留代码
        // deepSeekRadio = new JRadioButton("DeepSeek AI翻译");
        qianfanRadio = new JRadioButton("百度千帆 AI翻译 (免费)");
        
        ButtonGroup engineGroup = new ButtonGroup();
        engineGroup.add(youdaoRadio);
        engineGroup.add(baiduRadio);
        engineGroup.add(googleRadio);
        // 注释掉DeepSeek选项，隐藏但保留代码
        // engineGroup.add(deepSeekRadio);
        engineGroup.add(qianfanRadio);
        
        engineRow.add(engineLabel);
        engineRow.add(youdaoRadio);
        engineRow.add(Box.createHorizontalStrut(10));
        engineRow.add(baiduRadio);
        engineRow.add(Box.createHorizontalStrut(10));
        engineRow.add(googleRadio);
        engineRow.add(Box.createHorizontalStrut(10));
        // 注释掉DeepSeek选项，隐藏但保留代码
        // engineRow.add(deepSeekRadio);
        engineRow.add(Box.createHorizontalStrut(10));
        engineRow.add(qianfanRadio);
        
        enginePanel.add(engineRow);
        
        // -------- 翻译方向设置面板 --------
        JPanel directionPanel = new JPanel();
        directionPanel.setLayout(new BoxLayout(directionPanel, BoxLayout.Y_AXIS));
        directionPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "翻译方向", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        JPanel directionRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel directionLabel = new JLabel("选择方向:");
        directionLabel.setPreferredSize(new Dimension(80, 22));
        directionRow.add(directionLabel);
        
        String[] directions = {"英 -> 中", "日 -> 中", "韩 -> 中", "中 -> 英", "中 -> 日", "中 -> 韩",
                               "自动检测 -> 中", "自动检测 -> 英", "自动检测 -> 日", "自动检测 -> 韩"};
        translationDirectionCombo = new JComboBox<>(directions);
        translationDirectionCombo.setPreferredSize(new Dimension(180, 25));
        directionRow.add(translationDirectionCombo);
        
        directionPanel.add(directionRow);
        
        // 添加到翻译内容面板
        translationContent.add(enginePanel);
        translationContent.add(Box.createVerticalStrut(10));
        translationContent.add(directionPanel);
        
        translationPanel.add(translationContent, BorderLayout.NORTH);
        
        // ======== API密钥设置面板 ========
        JPanel apiKeyPanel = new JPanel(new BorderLayout(10, 10));
        apiKeyPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        JPanel apiKeyContent = new JPanel();
        apiKeyContent.setLayout(new BoxLayout(apiKeyContent, BoxLayout.Y_AXIS));
        
        // -------- 有道API设置面板 --------
        JPanel youdaoPanel = new JPanel();
        youdaoPanel.setLayout(new BoxLayout(youdaoPanel, BoxLayout.Y_AXIS));
        youdaoPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "有道翻译API设置", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        JPanel youdaoKeyRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel youdaoKeyLabel = new JLabel("App Key:");
        youdaoKeyLabel.setPreferredSize(new Dimension(80, 22));
        youdaoKeyRow.add(youdaoKeyLabel);
        
        youdaoAppKeyField = new JTextField();
        youdaoAppKeyField.setPreferredSize(new Dimension(250, 25));
        youdaoKeyRow.add(youdaoAppKeyField);
        youdaoPanel.add(youdaoKeyRow);
        
        JPanel youdaoSecretRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel youdaoSecretLabel = new JLabel("App Secret:");
        youdaoSecretLabel.setPreferredSize(new Dimension(80, 22));
        youdaoSecretRow.add(youdaoSecretLabel);
        
        youdaoAppSecretField = new JTextField();
        youdaoAppSecretField.setPreferredSize(new Dimension(250, 25));
        youdaoSecretRow.add(youdaoAppSecretField);
        youdaoPanel.add(youdaoSecretRow);
        
        // -------- 百度API设置面板 --------
        JPanel baiduPanel = new JPanel();
        baiduPanel.setLayout(new BoxLayout(baiduPanel, BoxLayout.Y_AXIS));
        baiduPanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "百度翻译API设置", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        JPanel baiduIdRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel baiduIdLabel = new JLabel("App ID:");
        baiduIdLabel.setPreferredSize(new Dimension(80, 22));
        baiduIdRow.add(baiduIdLabel);
        
        baiduAppIdField = new JTextField();
        baiduAppIdField.setPreferredSize(new Dimension(250, 25));
        baiduIdRow.add(baiduAppIdField);
        baiduPanel.add(baiduIdRow);
        
        JPanel baiduKeyRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel baiduKeyLabel = new JLabel("Security Key:");
        baiduKeyLabel.setPreferredSize(new Dimension(80, 22));
        baiduKeyRow.add(baiduKeyLabel);
        
        baiduSecurityKeyField = new JTextField();
        baiduSecurityKeyField.setPreferredSize(new Dimension(250, 25));
        baiduKeyRow.add(baiduSecurityKeyField);
        baiduPanel.add(baiduKeyRow);
        
        // -------- 谷歌API设置面板 --------
        JPanel googlePanel = new JPanel();
        googlePanel.setLayout(new BoxLayout(googlePanel, BoxLayout.Y_AXIS));
        googlePanel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(), "谷歌翻译API设置", TitledBorder.LEFT, TitledBorder.TOP,
            new Font("Dialog", Font.BOLD, 12)
        ));
        
        JPanel googleKeyRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        JLabel googleKeyLabel = new JLabel("API Key:");
        googleKeyLabel.setPreferredSize(new Dimension(80, 22));
        googleKeyRow.add(googleKeyLabel);
        
        googleApiKeyField = new JTextField();
        googleApiKeyField.setPreferredSize(new Dimension(250, 25));
        googleKeyRow.add(googleApiKeyField);
        googlePanel.add(googleKeyRow);
        
        // 添加到API密钥内容面板
        apiKeyContent.add(youdaoPanel);
        apiKeyContent.add(Box.createVerticalStrut(10));
        apiKeyContent.add(baiduPanel);
        apiKeyContent.add(Box.createVerticalStrut(10));
        apiKeyContent.add(googlePanel);
        
        // 使用滚动面板
        JScrollPane apiKeyScrollPane = new JScrollPane(apiKeyContent);
        apiKeyScrollPane.setBorder(null);
        apiKeyScrollPane.getVerticalScrollBar().setUnitIncrement(16);
        apiKeyPanel.add(apiKeyScrollPane, BorderLayout.CENTER);
        
        // 添加选项卡
        tabbedPane.addTab("外观", appearancePanel);
       // tabbedPane.addTab("翻译", translationPanel);
       // tabbedPane.addTab("API密钥", apiKeyPanel);
        
        // 添加按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        JButton applyButton = new JButton("应用");
        JButton closeButton = new JButton("关闭");
        
        // 设置按钮大小
        Dimension buttonSize = new Dimension(80, 30);
        applyButton.setPreferredSize(buttonSize);
        closeButton.setPreferredSize(buttonSize);
        
        applyButton.addActionListener(e -> {
            applySettings();
        });
        
        closeButton.addActionListener(e -> {
            try {
                String opacity = SettingContext.load(SETTING_CONF, "textbox.opacity");
                textBoxSetting.setOpacity(Float.valueOf(opacity));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            dispose();
        });
        
        buttonPanel.add(applyButton);
        buttonPanel.add(closeButton);
        
        // 添加到对话框
        add(tabbedPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 设置对话框属性
        setSize(450, 650);
        setLocationRelativeTo(getParent());
        setResizable(true);
        setModal(true);
    }
    
    /**
     * 获取与背景对比的文字颜色
     * @param background 背景颜色
     * @return 适合的文字颜色（黑色或白色）
     */
    private Color getContrastColor(Color background) {
        double luminance = (0.299 * background.getRed() + 0.587 * background.getGreen() + 0.114 * background.getBlue()) / 255;
        return luminance > 0.5 ? Color.BLACK : Color.WHITE;
    }
    
    /**
     * 根据边框样式更新背景图片设置区域的启用状态
     * 当使用科技边框或终端边框时，禁用背景图片设置
     */
    private void updateBackgroundImageSettingsState() {
        try {
            // 获取当前界面上选择的边框样式
            int borderStyle = borderStyleCombo.getSelectedIndex();
            
            // 科技边框为5，终端边框为6
            boolean isSpecialBorder = (borderStyle == 5 || borderStyle == 6);
            
            // 如果是特殊边框，禁用背景图片设置区域
            if (isSpecialBorder) {
                // 禁用背景图片选择按钮和单选按钮
                backgroundImageButton.setEnabled(false);
                enableBgImageRadio.setEnabled(false);
                disableBgImageRadio.setEnabled(false);
                
                // 设置提示信息
                backgroundImageButton.setText("科技/终端边框不支持背景图片");
                
                // 选择禁用背景图片选项
                disableBgImageRadio.setSelected(true);
            } else {
                // 如果不是特殊边框，启用背景图片设置区域
                backgroundImageButton.setEnabled(true);
                enableBgImageRadio.setEnabled(true);
                disableBgImageRadio.setEnabled(true);
                
                // 还原按钮文本
                try {
                    Properties p = new Properties();
                    File file = new File(SETTING_CONF);
                    if (file.exists()) {
                        p.load(file.toURI().toURL().openStream());
                        
                        String imagePath = p.getProperty("textbox.background.image", "");
                        if (imagePath.isEmpty()) {
                            backgroundImageButton.setText("选择图片");
                        } else {
                            backgroundImageButton.setText("图片已选择");
                        }
                        
                        // 根据设置选择合适的单选按钮
                        boolean useBackgroundImage = Boolean.parseBoolean(p.getProperty("textbox.background.image.enabled", "false"));
                        enableBgImageRadio.setSelected(useBackgroundImage);
                        disableBgImageRadio.setSelected(!useBackgroundImage);
                    }
                } catch (Exception e) {
                    System.err.println("读取背景图片设置时出错: " + e.getMessage());
                    backgroundImageButton.setText("选择图片");
                }
            }
        } catch (Exception e) {
            System.err.println("更新背景图片设置状态时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 加载当前设置
     */
    private void loadCurrentSettings() {
        try {
            // 加载字体设置
            if (textBoxSetting != null && textBoxSetting.getFontSetting() != null) {
                int fontSize = textBoxSetting.getFontSetting().getSize();
                fontSizeField.setText(String.valueOf(fontSize));
                
                if (textBoxSetting.getFontSetting().getFont() != null) {
                    String fontName = textBoxSetting.getFontSetting().getFont().getFamily();
                    fontFamilyCombo.setSelectedItem(fontName);
                    
                    // 加载字体样式
                    int fontStyle = textBoxSetting.getFontSetting().getFont().getStyle();
                    switch (fontStyle) {
                        case Font.BOLD:
                            fontStyleCombo.setSelectedIndex(1); // 粗体
                            break;
                        case Font.ITALIC:
                            fontStyleCombo.setSelectedIndex(2); // 斜体
                            break;
                        case Font.BOLD | Font.ITALIC:
                            fontStyleCombo.setSelectedIndex(3); // 粗斜体
                            break;
                        default:
                            fontStyleCombo.setSelectedIndex(0); // 常规
                            break;
                    }
                }
            }
            
            // 加载其他设置
            Properties p = new Properties();
            File file = new File(SETTING_CONF);
            if (file.exists()) {
                p.load(file.toURI().toURL().openStream());
                
                // 从配置文件加载颜色设置
                String fgColorV = p.getProperty("textbox.foreground.color");
                if (fgColorV != null && !fgColorV.isEmpty()) {
                    String[] colorSplits = fgColorV.split(",");
                    if (colorSplits.length == 3) {
                        int red = Integer.parseInt(colorSplits[0]);
                        int green = Integer.parseInt(colorSplits[1]);
                        int blue = Integer.parseInt(colorSplits[2]);
                        textColor = new Color(red, green, blue);
                        textColorButton.setBackground(textColor);
                        textColorButton.setForeground(getContrastColor(textColor));
                        
                        // 更新TextBoxSetting对象
                        if (textBoxSetting != null) {
                            Integer[] foreground = new Integer[3];
                            foreground[0] = red;
                            foreground[1] = green;
                            foreground[2] = blue;
                            textBoxSetting.setForeground(foreground);
                        }
                    }
                } else if (textBoxSetting != null && textBoxSetting.getForeground() != null && textBoxSetting.getForeground().length == 3) {
                    // 如果配置文件中没有，则使用textBoxSetting中的设置
                    textColor = new Color(
                        textBoxSetting.getForeground()[0],
                        textBoxSetting.getForeground()[1],
                        textBoxSetting.getForeground()[2]
                    );
                    textColorButton.setBackground(textColor);
                    textColorButton.setForeground(getContrastColor(textColor));
                }
                
                String bgColorV = p.getProperty("textbox.background.color");
                if (bgColorV != null && !bgColorV.isEmpty()) {
                    String[] colorSplits = bgColorV.split(",");
                    if (colorSplits.length == 3) {
                        int red = Integer.parseInt(colorSplits[0]);
                        int green = Integer.parseInt(colorSplits[1]);
                        int blue = Integer.parseInt(colorSplits[2]);
                        backgroundColor = new Color(red, green, blue);
                        backgroundColorButton.setBackground(backgroundColor);
                        backgroundColorButton.setForeground(getContrastColor(backgroundColor));
                        
                        // 更新TextBoxSetting对象
                        if (textBoxSetting != null) {
                            if (textBoxSetting.getBackgroundSetting() == null) {
                                TextBoxSetting.BackgroundSetting bgSetting = new TextBoxSetting.BackgroundSetting();
                                textBoxSetting.setBackgroundSetting(bgSetting);
                            }
                            
                            Integer[] bgColor = new Integer[3];
                            bgColor[0] = red;
                            bgColor[1] = green;
                            bgColor[2] = blue;
                            textBoxSetting.getBackgroundSetting().setColor(bgColor);
                        }
                    }
                } else if (textBoxSetting != null && 
                    textBoxSetting.getBackgroundSetting() != null && 
                    textBoxSetting.getBackgroundSetting().getColor() != null && 
                    textBoxSetting.getBackgroundSetting().getColor().length == 3) {
                    // 如果配置文件中没有，则使用textBoxSetting中的设置
                    backgroundColor = new Color(
                        textBoxSetting.getBackgroundSetting().getColor()[0],
                        textBoxSetting.getBackgroundSetting().getColor()[1],
                        textBoxSetting.getBackgroundSetting().getColor()[2]
                    );
                    backgroundColorButton.setBackground(backgroundColor);
                    backgroundColorButton.setForeground(getContrastColor(backgroundColor));
                }
                
                // 加载透明度设置
                String opacityStr = p.getProperty("textbox.opacity", "0.8");
                try {
                    float opacity = Float.parseFloat(opacityStr);
                    // 确保透明度在合理范围内
                    opacity = Math.max(0.2f, Math.min(1.0f, opacity));
                    opacitySlider.setValue((int)(opacity * 100));
                    
                    // 更新TextBoxSetting对象
                    if (textBoxSetting != null) {
                        textBoxSetting.setOpacity(opacity);
                    }
                } catch (NumberFormatException ex) {
                    System.err.println("解析透明度值出错: " + ex.getMessage());
                    opacitySlider.setValue(100);
                }
                
                // 加载背景图片设置
                backgroundImagePath = p.getProperty("textbox.background.image", "");
                if (!backgroundImagePath.isEmpty()) {
                    backgroundImageButton.setText("图片已选择");
                }
                
                useBackgroundImage = Boolean.parseBoolean(p.getProperty("textbox.background.image.enabled", "false"));
                if (useBackgroundImage) {
                    enableBgImageRadio.setSelected(true);
                } else {
                    disableBgImageRadio.setSelected(true);
                }
                
                // 加载边框样式
                String borderStyleStr = p.getProperty("textbox.border.style", "0");
                try {
                    int borderStyle = Integer.parseInt(borderStyleStr);
                    borderStyleCombo.setSelectedIndex(borderStyle);
                } catch (NumberFormatException ex) {
                    borderStyleCombo.setSelectedIndex(0);
                }
                
                // 根据边框样式更新背景图片设置区域的状态
                updateBackgroundImageSettingsState();
                
                // 加载翻译引擎设置
                String engine = p.getProperty("textbox.translation.engine", "QIANFAN");
                if ("YOUDAO".equals(engine)) {
                    youdaoRadio.setSelected(true);
                } else if ("BAIDU".equals(engine)) {
                    baiduRadio.setSelected(true);
                } else if ("GOOGLE".equals(engine)) {
                    googleRadio.setSelected(true);
                } else if ("DEEPSEEK".equals(engine)) {
                    // DeepSeek设置逻辑保留，但如果选择了DeepSeek，默认使用千帆
                    // deepSeekRadio.setSelected(true);
                    qianfanRadio.setSelected(true);
                } else if ("QIANFAN".equals(engine)) {
                    qianfanRadio.setSelected(true);
                } else {
                    qianfanRadio.setSelected(true);
                }
                
                // 加载翻译方向设置
                String direction = p.getProperty("textbox.translation.direction", "EN2CN");
                switch (direction) {
                    case "EN2CN":
                        translationDirectionCombo.setSelectedIndex(0);
                        break;
                    case "JA2CN":
                        translationDirectionCombo.setSelectedIndex(1);
                        break;
                    case "KR2CN":
                        translationDirectionCombo.setSelectedIndex(2);
                        break;
                    case "CN2EN":
                        translationDirectionCombo.setSelectedIndex(3);
                        break;
                    case "CN2JA":
                        translationDirectionCombo.setSelectedIndex(4);
                        break;
                    case "CN2KR":
                        translationDirectionCombo.setSelectedIndex(5);
                        break;
                    case "AUTO2CN":
                        translationDirectionCombo.setSelectedIndex(6);
                        break;
                    case "AUTO2EN":
                        translationDirectionCombo.setSelectedIndex(7);
                        break;
                    case "AUTO2JA":
                        translationDirectionCombo.setSelectedIndex(8);
                        break;
                    case "AUTO2KR":
                        translationDirectionCombo.setSelectedIndex(9);
                        break;
                    default:
                        translationDirectionCombo.setSelectedIndex(0);
                        break;
                }
            }
            
            // 加载API密钥设置
            if (keySetting != null) {
                if (keySetting.getYoudao() != null) {
                    youdaoAppKeyField.setText(keySetting.getYoudao().getAppKey());
                    youdaoAppSecretField.setText(keySetting.getYoudao().getAppSecret());
                }
                
                if (keySetting.getBaidu() != null) {
                    baiduAppIdField.setText(keySetting.getBaidu().getAppId());
                    baiduSecurityKeyField.setText(keySetting.getBaidu().getSecurityKey());
                }
            }
            
        } catch (Exception e) {
            System.err.println("加载设置时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 应用设置
     */
    private void applySettings() {
        try {
            // 应用字体设置
            String fontFamily = (String) fontFamilyCombo.getSelectedItem();
            int fontSize = Integer.parseInt(fontSizeField.getText());
            SettingContext.store(SETTING_CONF, "textbox.font.name", fontFamily);
            SettingContext.store(SETTING_CONF, "textbox.font.size", String.valueOf(fontSize));
            
            // 应用字体样式设置
            int fontStyle;
            switch (fontStyleCombo.getSelectedIndex()) {
                case 1:
                    fontStyle = Font.BOLD;
                    break;
                case 2:
                    fontStyle = Font.ITALIC;
                    break;
                case 3:
                    fontStyle = Font.BOLD | Font.ITALIC;
                    break;
                default:
                    fontStyle = Font.PLAIN;
                    break;
            }
            SettingContext.store(SETTING_CONF, "textbox.font.style", String.valueOf(fontStyle));
            
            // 应用颜色设置
            if (textColor != null) {
                String textColorStr = textColor.getRed() + "," + textColor.getGreen() + "," + textColor.getBlue();
                SettingContext.store(SETTING_CONF, "textbox.foreground.color", textColorStr);
                
                // 更新TextBoxSetting对象中的前景色
                Integer[] foreground = new Integer[3];
                foreground[0] = textColor.getRed();
                foreground[1] = textColor.getGreen();
                foreground[2] = textColor.getBlue();
                textBoxSetting.setForeground(foreground);
            }
            
            if (backgroundColor != null) {
                String bgColorStr = backgroundColor.getRed() + "," + backgroundColor.getGreen() + "," + backgroundColor.getBlue();
                SettingContext.store(SETTING_CONF, "textbox.background.color", bgColorStr);
                
                // 更新TextBoxSetting对象中的背景色
                if (textBoxSetting.getBackgroundSetting() != null) {
                    Integer[] bgColor = new Integer[3];
                    bgColor[0] = backgroundColor.getRed();
                    bgColor[1] = backgroundColor.getGreen();
                    bgColor[2] = backgroundColor.getBlue();
                    textBoxSetting.getBackgroundSetting().setColor(bgColor);
                } else {
                    TextBoxSetting.BackgroundSetting bgSetting = new TextBoxSetting.BackgroundSetting();
                    Integer[] bgColor = new Integer[3];
                    bgColor[0] = backgroundColor.getRed();
                    bgColor[1] = backgroundColor.getGreen();
                    bgColor[2] = backgroundColor.getBlue();
                    bgSetting.setColor(bgColor);
                    textBoxSetting.setBackgroundSetting(bgSetting);
                }
            }
            
            // 应用透明度设置
            float opacity = opacitySlider.getValue() / 100.0f;
            // 确保透明度在合理范围内
            opacity = Math.max(0.2f, Math.min(1.0f, opacity));
            SettingContext.store(SETTING_CONF, "textbox.opacity", String.valueOf(opacity));
            textBoxSetting.setOpacity(opacity);
            
            // 应用透明度到窗口
            if (textBox != null) {
                JFrame frame = textBox.getJFrame();
                if (frame != null) {
                    // 确保窗口是无装饰的
                    if (!frame.isUndecorated()) {
                        frame.dispose();
                        frame.setUndecorated(true);
                        frame.setVisible(true);
                    }
                    textBox.safelySetOpacity(frame, opacity);
                }
            }
            
            // 应用边框样式设置
            int borderStyle = borderStyleCombo.getSelectedIndex();
            SettingContext.store(SETTING_CONF, "textbox.border.style", String.valueOf(borderStyle));
            
            // 应用背景图片设置 - 只有在非特殊边框时才应用背景图片设置
            boolean isSpecialBorder = (borderStyle == 5 || borderStyle == 6);
            if (!isSpecialBorder) {
                boolean useBgImage = enableBgImageRadio.isSelected();
                SettingContext.store(SETTING_CONF, "textbox.background.image.enabled", String.valueOf(useBgImage));
                
                if (backgroundImagePath != null && !backgroundImagePath.isEmpty()) {
                    SettingContext.store(SETTING_CONF, "textbox.background.image", backgroundImagePath);
                }
            } else {
                // 如果是特殊边框，强制禁用背景图片
                SettingContext.store(SETTING_CONF, "textbox.background.image.enabled", "false");
            }
            
            // 应用翻译引擎设置
            String engine = "QIANFAN";
            if (youdaoRadio.isSelected()) {
                engine = "YOUDAO";
            } else if (baiduRadio.isSelected()) {
                engine = "BAIDU";
            } else if (googleRadio.isSelected()) {
                engine = "GOOGLE";
            // } else if (deepSeekRadio.isSelected()) {
            //     engine = "DEEPSEEK";
            } else if (qianfanRadio.isSelected()) {
                engine = "QIANFAN";
            }
            SettingContext.store(SETTING_CONF, "textbox.translation.engine", engine);
            
            // 应用翻译方向设置
            String direction = "EN2CN";
            switch (translationDirectionCombo.getSelectedIndex()) {
                case 0:
                    direction = "EN2CN";
                    break;
                case 1:
                    direction = "JA2CN";
                    break;
                case 2:
                    direction = "KR2CN";
                    break;
                case 3:
                    direction = "CN2EN";
                    break;
                case 4:
                    direction = "CN2JA";
                    break;
                case 5:
                    direction = "CN2KR";
                    break;
                case 6:
                    direction = "AUTO2CN";
                    break;
                case 7:
                    direction = "AUTO2EN";
                    break;
                case 8:
                    direction = "AUTO2JA";
                    break;
                case 9:
                    direction = "AUTO2KR";
                    break;
            }
            SettingContext.store(SETTING_CONF, "textbox.translation.direction", direction);
            
            // 应用API密钥设置
            if (keySetting != null) {
                if (keySetting.getYoudao() != null) {
                    keySetting.getYoudao().setAppKey(youdaoAppKeyField.getText().trim());
                    keySetting.getYoudao().setAppSecret(youdaoAppSecretField.getText().trim());
                }
                
                if (keySetting.getBaidu() != null) {
                    keySetting.getBaidu().setAppId(baiduAppIdField.getText().trim());
                    keySetting.getBaidu().setSecurityKey(baiduSecurityKeyField.getText().trim());
                }
            }
            
            // 重新加载设置并应用到TextBox
            textBox.applySettings();
            
        } catch (Exception e) {
            System.err.println("应用设置时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 